#!/usr/bin/env python

from . import VIRTUALROOT
from datetime import datetime as dt

class Path(object):

    def __init__(self, srf):
        self.virtualroot = os.path.join(os.getenv('HOME'), 'VIRTUALROOT')
        #self.prepend = 'vbkp'
        datestring = dt.today().strftime('%d-%m-%Y')
        self.append = '_{0}_srf:{1}_date:{2}'.format('vbkp', srf, datestring)

    def _check(self, fullpath):
        if not os.path.isdir(VIRTUALROOT):
            sys.stderr.write('path not found\n')

    def virtualroot(self):
        os.mkdir(virtualroot)

    def makeintermediate(self, virtualdirpath):
        if not os.path.isdir(virtualdirpath):
            try:
                os.makedirs(virtualdirpath)
            except Exception, e:
                print(e)
                print('exception end at INTER')
    #def getvirtualpath(self, rootpath):
    #    return os.path.join(self.virtualroot, rootpath)

    def getcopyvirtualpath(self, filename):
        #join wont work with leading '/'
        filename = filename.lstrip('/')
        return os.path.join(self.virtualroot, filename)

    def copyfile(self, fullpath):
        abspath = os.path.abspath(fullpath)
        if not os.path.exists(abspath):
            sys.stderr.write('File not found, you might be in wrong directory')
        if os.path.isdir(abspath):
            shutil.copytree(abspath, self.getcopyvirtualpath(abspath), symlinks=True)
        elif os.path.isfile(abspath):
            dirpath, filename = os.path.split(abspath)
            vfilename = '{}{}'.format(filename, self.append)
            vabspath = os.path.join(dirpath, vfilename)
            self.makeintermediate(self.getcopyvirtualpath(dirpath))
            try:
                print('copying...')
                print(self.getcopyvirtualpath(vabspath))
                shutil.copy2(abspath, self.getcopyvirtualpath(vabspath)) 
            except Exception, e:
                print('error while copying')
                print(e)


class Backup(object):

    def __init__(self):
        pass

    def createcopy(self, sourcepath, prepend, append):
        pass


if __name__ == '__main__':
    import shutil, os, filecmp, sys
    try:
        import argparse
    except Exception, e:
        sys.err.write('no arg parse module')
        sys.exit(1) 
    parser = argparse.ArgumentParser(description='Policy conforming backup.')
    parser.add_argument('-s', '--srf', help='The Service request Number')
    parser.add_argument('-d', '--directories', help='mandatory arg WITHOUT dash')
    parser.add_argument('-f' '--files', help='optional with dash (-)')
    args = parser.parse_args()
    try:
        os.mkdir(virtualroot)
    except Exception, e:
        sys.stderr.write('virtualroot already created.\n')
    
    p = Path(args.srf)
    p._check('/etc/init.d')
    abspath = os.path.abspath('grep.py')
    p.copyfile('grep.py')
